package cn.soulic.tools.redis.migration.config;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * Redis客户端连接配置
 *
 * @author Soulic Yang
 * @since 1.0.0
 */
@Configuration
public class RedisMigrationConfiguration {
    private static final long REDIS_CONNECTION_TIMEOUT = 5000L;

    @Bean
    public RedisClient sourceRedisClient(RedisMigrationProperties properties) {
        return createRedisClient(properties.getSource());
    }

    @Bean
    public RedisClient targetRedisClient(RedisMigrationProperties properties) {
        return createRedisClient(properties.getTarget());
    }

    @Bean
    public StatefulRedisConnection<String, String> sourceConnection(RedisClient sourceRedisClient) {
        return sourceRedisClient.connect();
    }

    @Bean
    public StatefulRedisConnection<String, String> targetConnection(RedisClient targetRedisClient) {
        return targetRedisClient.connect();
    }

    @Bean
    public RedisCommands<String, String> sourceCommands(StatefulRedisConnection<String, String> sourceConnection) {
        return sourceConnection.sync();
    }

    @Bean
    public RedisCommands<String, String> targetCommands(StatefulRedisConnection<String, String> targetConnection) {
        return targetConnection.sync();
    }

    private RedisClient createRedisClient(RedisMigrationProperties.RedisServer serverProperties) {
        RedisURI.Builder builder = RedisURI.builder()
                .withHost(serverProperties.getHost())
                .withPort(serverProperties.getPort())
                .withDatabase(serverProperties.getDatabase())
                .withTimeout(Duration.ofMillis(REDIS_CONNECTION_TIMEOUT));
        if (StringUtils.hasText(serverProperties.getPassword())) {
            builder.withPassword(serverProperties.getPassword().toCharArray());
        }

        RedisURI uri = builder.build();
        return RedisClient.create(uri);
    }
}
